<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户列表
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection"
                    v-if="false">批量删除</el-button>
                <el-input @input="searchUserFunc" v-model="query.name" placeholder="搜索姓名/登录名"
                    class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-Plus" @click="dialogFormVisible = true">
                    添加用户
                </el-button>
                <el-button type="warning" icon="el-icon-delete" @click="deleteUserFunc">
                    删除用户
                </el-button>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" type="index" width="55" align="center"></el-table-column>
                <el-table-column prop="user_acc" label="账号"></el-table-column>
                <el-table-column prop="user_name" label="姓名"></el-table-column>
                <el-table-column prop="role" label="角色"></el-table-column>
                <el-table-column prop="user_create_time" label="创建时间"></el-table-column>
                <el-table-column prop="user_id" label="用户ID"></el-table-column>
            </el-table>
            <div style="margin-top:20px;">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 20, 30]" :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
                </el-pagination>
            </div>
        </div>

        <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
            <div class="my-user-form">
                <el-form :model="form">
                    <p>账号：</p>
                    <el-form-item>
                        <el-input v-model="form.user_acc" autocomplete="off"></el-input>
                    </el-form-item>
                    <p>姓名：</p>
                    <el-form-item>
                        <el-input v-model="form.user_name" autocomplete="off" placeholder=""></el-input>
                    </el-form-item>
                    <p>密码</p>
                    <el-form-item>
                        <el-input v-model="form.user_pwd" autocomplete="off" type="password"
                            placeholder=""></el-input>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmAddUser">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getUserList, getUserTotal, searchUser, deleteUser, register } from '../../api/index';
import moment from 'moment';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 5
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            // 当前页
            currentPage: 0,
            // 删除目标
            userArr: [],
            // 是否弹窗“添加用户”
            dialogFormVisible: false,
            // 用户信息
            form: {
                user_acc: '',
                user_name: '',
                user_pwd: '',
            },
        };
    },
    created() {
        this.getData();
    },
    methods: {
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.getData(val, 5);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.getData(val, 5);
        },
        // 获取 easy-mock 的模拟数据
        getData(page_num = 1, page_size = 5) {
            // 用户列表
            getUserList({ page_num, page_size }).then(content => {
                console.log('x.0', content)
                let { code, msg, result, page } = content;
                if (code == 200) {
                    this.tableData = result;
                }
            })
                .catch(err => {
                    console.log(err);
                })
            // 总数
            getUserTotal().then(content => {
                console.log('y.0', content)
                let { code, msg, total } = content;
                if (code == 200) {
                    this.pageTotal = total;
                }
            })
                .catch(err => {
                    console.log(err);
                })

        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 点击删除
        async deleteUserFunc() {
            let arr = [];
            for (let i = 0; i < this.userArr.length; i++) {
                // 删除指定的数据
                await deleteUser({ user_id: this.userArr[i].user_id }).then(content => {
                    console.log('删除：', content)
                    if (content.code == 200) {
                        arr = this.tableData.filter(item => {
                            if (item.user_id != this.userArr[i].user_id) {
                                return item;
                            }
                        })
                    }
                })
                    .catch(
                        err => {
                            console.log(err);
                        }
                    )
                console.log(11, arr)
                // 重新赋值
                this.tableData = [...arr];
            }
        },

        // 添加用户
        async confirmAddUser() {
            let user_acc = this.form.user_acc;
            let pwd = this.form.user_pwd;
            let user_name = this.form.user_name;
            let time = moment((new Date().getTime())).format("YYYY-MM-DD hh:mm:ss");
            register({ user_acc, user_pwd: pwd, user_name, user_create_time: time }).then(content => {
                let { code, msg, token } = content;
                if (code == 200) {
                    // 缓存用户令牌
                    localStorage.setItem('auto_token', token);
                    // 弹窗提示
                    this.$message({
                        message: "添加用户成功。",
                        type: 'success'
                    });

                    this.getData();
                }
                else {
                    // 弹窗提示
                    this.$message({
                        message: '添加用户失败。',
                        type: 'warning'
                    });
                }
                // 隐藏弹窗
                this.dialogFormVisible = false;
            })
        },
        // 搜索用户
        async searchUserFunc() {
            let keyword = this.query.name;
            if (keyword.length == 0) {
                this.getData();
                return;
            }
            await searchUser({ keyword }).then(content => {
                console.log('搜索结果:', content)
                let { code, msg, result } = content;
                if (code == 200) {
                    this.tableData = result;
                    this.pageTotal = result.length;
                }
            })
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.userArr = val;
            console.log({ val })
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData(val, 5);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
